'''
Created on Jun 2, 2010

@author: yglazner
'''
from pymock import PyMockTestCase
import unittest
from wp import Worker
from wp.client import RWorker, WorkerPool
from multiprocessing import Process
from thread import LockType
import time

class TestRWorker(PyMockTestCase):
    
    def setUp(self):
        PyMockTestCase.setUp(self)
        self.p = Process(target=Worker().start,args=(50000, 'cool'))
        self.p.start()
        self.pool = WorkerPool([])
        self.rworker = RWorker('localhost', self.pool,'cool')

    def tearDown(self):
        PyMockTestCase.tearDown(self)
        self.p.terminate()
        self.pool.close()
        
    def test__init__(self):
        self.assertEqual(self.rworker.host,'localhost') 
        self.assertEqual(self.rworker.pool,self.pool) 
        assert isinstance(self.rworker._lock,LockType)
        self.assertEqual(self.rworker._worker,None) 
        self.assertEqual(self.rworker._hired,False) 

        
    def testConnect(self):
        l = []
        self.pool.addActiveWorker = lambda a:l.append(a)
        self.rworker.connect()
        time.sleep(2)
        self.assertNotEqual(self.rworker._worker,None)
        self.assertEqual(self.rworker,l[0])
    
    def testExecute(self):
        args = 1,2,3,4,5
        kw = {'1':1,'2':2,'3':3,'4':4}
        
        self.rworker._worker = worker = self.mock()
        res=worker.execute_remote_task(*args,**kw)
        self.replay()
        assert self.rworker.execute(*args,**kw) == res
        self.verify()
    
    def testHire(self):
        lock = self.rworker._lock = self.mock()
        with lock:
            pass
        self.replay()
        assert self.rworker.hire()
        self.verify()
        
    def testHire_busy(self):
        self.rworker._hired = True
        lock = self.rworker._lock = self.mock()
        with lock:pass
        self.replay()
        assert self.rworker.hire() is False
        self.verify()
        
    def testFire(self):
        self.rworker.hire()
        lock = self.rworker._lock = self.mock()
        with lock:pass
        self.replay()
        self.rworker.fire()
        self.verify()
        assert self.rworker._hired is False

if __name__ == "__main__":
    #import sys;sys.argv = ['', 'Test.testName']
    unittest.main()